using System;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Collections;
using System.Runtime.CompilerServices;

namespace AnimCollections {
    public unsafe struct UnsafeArrayReader<T> : IDisposable where T : unmanaged {

        [NativeDisableUnsafePtrRestriction]
        internal T* buffer;
        internal int length;
        internal AllocatorManager.AllocatorHandle allocatorHandle;

        public int Length => length;

        public readonly bool IsCreated {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => buffer != null;
        }

        internal UnsafeArrayReader(T* buffer, int length, AllocatorManager.AllocatorHandle allocator) {
            this.buffer = buffer;
            this.length = length;
            allocatorHandle = allocator;
        }

        public void Dispose() {
            if (IsCreated) {
                if (allocatorHandle.ToAllocator > Allocator.None) {
                    Memory.Unmanaged.Free(buffer, allocatorHandle);
                    allocatorHandle = AllocatorManager.Invalid;
                }

                buffer = null;
                length = 0;
            }
        }

        public unsafe ref T this[int index] {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get {
                return ref buffer[CollectionHelper.AssumePositive(index)];
            }

        }
    }
}
